document.addEventListener('DOMContentLoaded', init);

function init() {
  // 从URL获取月份参数
  const urlParams = new URLSearchParams(window.location.search);
  const monthParam = urlParams.get('month');
  const initialMonth = monthParam ? new Date(parseInt(monthParam)) : new Date();
  
  // 初始化月份选择器
  initMonthSelector(initialMonth);
  
  // 加载数据
  loadData(initialMonth);
}

function initMonthSelector(initialMonth) {
  const selector = document.getElementById('month-selector');
  const months = [];
  const now = new Date();
  
  // 生成最近12个月选项
  for (let i = -6; i <= 6; i++) {
    const date = new Date(now.getFullYear(), now.getMonth() + i, 1);
    months.push(date);
  }

  months.forEach(date => {
    const option = document.createElement('option');
    option.value = date.getTime();
    option.textContent = `${date.getFullYear()}年${date.getMonth() + 1}月`;
    if (date.getTime() === initialMonth.getTime()) {
      option.selected = true;
    }
    selector.appendChild(option);
  });

  // 月份切换事件
  selector.addEventListener('change', (e) => {
    loadData(new Date(parseInt(e.target.value)));
  });
}

function loadData(targetMonth) {
  const year = targetMonth.getFullYear();
  const month = targetMonth.getMonth();
  
  // 计算当月时间范围
  const startTime = new Date(year, month, 1).getTime();
  const endTime = new Date(year, month + 1, 0).getTime();
  
  // 发送历史记录请求
  chrome.runtime.sendMessage({
    action: "getHistory",
    startTime,
    endTime
  }, (response) => {
    if (response && response.dailyHours) {
      renderChart(response.dailyHours, targetMonth);
      calculateStats(response.dailyHours, targetMonth);
    }
  });
}

function renderChart(dailyHours, targetMonth) {
  const chartDom = document.getElementById('chart');
  const chart = echarts.init(chartDom);
  
  // 生成当月所有日期
  const daysInMonth = new Date(
    targetMonth.getFullYear(), 
    targetMonth.getMonth() + 1, 
    0
  ).getDate();
  
  const fullData = [];
  for (let day = 1; day <= daysInMonth; day++) {
    const dateStr = `${targetMonth.getFullYear()}-${(targetMonth.getMonth()+1).toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
    const existing = dailyHours.find(d => d.date === dateStr);
    fullData.push(existing || {
      date: dateStr,
      hours: 0,
      isWeekend: new Date(dateStr).getDay() % 6 === 0
    });
  }

  // 全屏优化后的图表配置
  const option = {
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(30, 30, 50, 0.9)',
      borderColor: '#8f94fb',
      borderWidth: 1,
      padding: [10, 15],
      textStyle: {
        color: '#e6e6ff',
        fontSize: 16,
        fontWeight: 'normal'
      },
      formatter: (params) => {
        const data = params[0];
        const date = new Date(data.name);
        return `
          <div style="margin-bottom:5px;font-size:18px;font-weight:bold;">
            ${date.getMonth()+1}月${date.getDate()}日 (${['日','一','二','三','四','五','六'][date.getDay()]})
          </div>
          <div style="display:flex;align-items:center;">
            <div style="height:16px;width:16px;background:${data.color};border-radius:3px;margin-right:8px;"></div>
            <div style="font-size:16px;flex-grow:1;">工作时长: <b style="font-size:18px;">${data.value} 小时</b></div>
          </div>
          <div style="margin-top:10px;font-size:14px;">
            ${data.value >= 8 
              ? '<span style="color:#62f74c;">✓ 达到8小时目标</span>' 
              : data.value > 0 
                ? `<span style="color:#ff6b6b;">✗ 还差${(8 - data.value).toFixed(1)}小时</span>` 
                : '<span style="color:#aaa;">无工作记录</span>'}
          </div>
        `;
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: fullData.map(d => d.date),
      axisLine: {
        lineStyle: {
          color: '#4a5568'
        }
      },
      axisLabel: {
        color: '#a0aec0',
        fontSize: 14,
        formatter: value => new Date(value).getDate()
      },
      splitLine: {
        show: false
      }
    },
    yAxis: {
      type: 'value',
      name: '工作时长 (小时)',
      nameTextStyle: {
        color: '#a0aec0',
        fontSize: 16,
        padding: [0, 50, 0, 0]
      },
      max: 12,
      axisLine: {
        lineStyle: {
          color: '#4a5568'
        }
      },
      axisLabel: {
        color: '#a0aec0',
        fontSize: 14
      },
      splitLine: {
        lineStyle: {
          color: '#2d3748',
          type: 'dashed'
        }
      }
    },
    series: [{
      data: fullData.map(d => ({
        value: d.hours,
        itemStyle: {
          color: d.isWeekend 
            ? '#4ade80' // 周末 
            : d.hours >= 8 
              ? '#4e54c8' // 达标日
              : d.hours > 0 
                ? '#f87171' // 未达标
                : '#718096' // 无记录
        }
      })),
      type: 'bar',
      barWidth: '20',
      label: {
        show: true,
        position: 'top',
        formatter: (params) => {
          if(params.value > 0) {
            return `${params.value}`;
          }
          return '';
        },
        color: '#fff',
        fontWeight: 'bold',
        fontSize: 14
      },
      showBackground: true,
      backgroundStyle: {
        color: 'rgba(45, 55, 73, 0.8)'
      }
    }],
    dataZoom: [{
      type: 'inside',
      start: 0,
      end: 100,
      zoomLock: false
    }, {
      type: 'slider',
      show: true,
      xAxisIndex: [0],
      start: 0,
      end: 100,
      height: 20,
      bottom: 0,
      backgroundColor: 'rgba(45, 55, 73, 0.8)',
      borderColor: 'transparent',
      fillerColor: 'rgba(78, 84, 200, 0.3)',
      dataBackground: {
        lineStyle: {
          color: '#4a5568',
          width: 1
        },
        areaStyle: {
          color: '#2d3748'
        }
      },
      textStyle: {
        color: '#a0aec0'
      }
    }],
    animation: true,
    animationDuration: 1000,
    animationEasing: 'cubicOut'
  };

  chart.setOption(option);
  
  // 窗口大小变化时重绘图表
  window.addEventListener('resize', () => chart.resize());
}

function calculateStats(dailyHours, targetMonth) {
  // 计算工作日天数（排除周末）
  const year = targetMonth.getFullYear();
  const month = targetMonth.getMonth();
  const start = new Date(year, month, 1);
  const end = new Date(year, month + 1, 0);
  
  let workDays = 0;
  for (let d = new Date(start); d <= end; d.setDate(d.getDate() + 1)) {
    if (d.getDay() !== 0 && d.getDay() !== 6) workDays++;
  }
  
  const expectedHours = workDays * 8;
  const actualHours = dailyHours.reduce((sum, day) => sum + day.hours, 0);
  const completion = Math.min(100, Math.round((actualHours / expectedHours) * 100));
  
  // 更新UI
  document.getElementById('expected-hours').textContent = `${expectedHours} 小时`;
  document.getElementById('actual-hours').textContent = `${actualHours.toFixed(1)} 小时`;
  document.getElementById('completion').textContent = `${completion}%`;
  
  // 为完成度添加颜色
  const completionEl = document.getElementById('completion');
  completionEl.style.color = 
    completion >= 100 ? '#62f74c' : 
    completion > 80 ? '#ffce44' : 
    '#ff6b6b';
    
  // 添加小图标
  completionEl.innerHTML += `${
    completion >= 100 ? ' <span style="color:#62f74c;">✓</span>' : 
    completion > 80 ? ' <span style="color:#ffce44;">↗</span>' : 
    ' <span style="color:#ff6b6b;">↙</span>'
  }`;
}